<?php
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type");

require_once 'db.php';

// 获取操作类型
$action = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = isset($_POST['action']) ? $_POST['action'] : '';
} else {
    $action = isset($_GET['action']) ? $_GET['action'] : '';
}

try {
    switch ($action) {
        // 获取教练详情
        case 'get_coach_detail':
            $id = isset($_GET['id']) ? intval($_GET['id']) : 0;
            if ($id <= 0) throw new Exception('参数错误');

            // 获取教练信息
            $sql = "SELECT c.*, cc.name as category_name 
                    FROM coaches c
                    LEFT JOIN coach_categories cc ON c.category_id = cc.id
                    WHERE c.id = ? AND c.status = 1";
            
            $stmt = $conn->prepare($sql);
            if ($stmt === false) {
                throw new Exception('SQL预处理失败: ' . $conn->error);
            }

            if (!$stmt->bind_param("i", $id)) {
                throw new Exception('参数绑定失败: ' . $stmt->error);
            }

            if (!$stmt->execute()) {
                throw new Exception('查询执行失败: ' . $stmt->error);
            }

            $result = $stmt->get_result();
            
            if ($result->num_rows > 0) {
                $coach = $result->fetch_assoc();
                echo json_encode([
                    'status' => 'success',
                    'coach' => $coach
                ]);
            } else {
                throw new Exception("教练不存在");
            }
            break;

        // 获取可用时间段
        case 'get_available_slots':
            $coach_id = isset($_GET['coach_id']) ? intval($_GET['coach_id']) : 0;
            $date = isset($_GET['date']) ? $_GET['date'] : date('Y-m-d');
            
            if ($coach_id <= 0) throw new Exception('参数错误');

            // 修改查询逻辑
            $sql = "SELECT t.time_slot,
                    CASE 
                        WHEN cs.id IS NULL THEN 'unscheduled'  -- 未排班
                        WHEN EXISTS (
                            SELECT 1 FROM bookings b 
                            WHERE b.coach_id = cs.coach_id 
                            AND b.booking_date = cs.date 
                            AND b.time_slot = cs.time_slot 
                            AND b.status < 3  -- 只检查未取消的预约
                        ) THEN 'booked'
                        WHEN cs.is_available = 1 THEN 'available'
                        ELSE 'unavailable'
                    END as status
                    FROM (
                        SELECT '09:00-10:00' as time_slot UNION ALL
                        SELECT '10:00-11:00' UNION ALL
                        SELECT '11:00-12:00' UNION ALL
                        SELECT '14:00-15:00' UNION ALL
                        SELECT '15:00-16:00' UNION ALL
                        SELECT '16:00-17:00' UNION ALL
                        SELECT '17:00-18:00' UNION ALL
                        SELECT '18:00-19:00' UNION ALL
                        SELECT '19:00-20:00'
                    ) t
                    LEFT JOIN coach_schedules cs ON cs.time_slot = t.time_slot 
                        AND cs.coach_id = ? AND cs.date = ?
                    ORDER BY t.time_slot";
            
            $stmt = $conn->prepare($sql);
            $stmt->bind_param("is", $coach_id, $date);
            $stmt->execute();
            $result = $stmt->get_result();
            
            $slots = [];
            while ($row = $result->fetch_assoc()) {
                $slots[] = $row;
            }
            
            echo json_encode([
                'status' => 'success',
                'slots' => $slots
            ]);
            break;

        // 创建预约
        case 'create_booking':
            // 获取请求参数
            $user_id = isset($_POST['user_id']) ? intval($_POST['user_id']) : 0;
            $coach_id = isset($_POST['coach_id']) ? intval($_POST['coach_id']) : 0;
            $type = isset($_POST['type']) ? intval($_POST['type']) : 0;
            $booking_date = isset($_POST['booking_date']) ? $_POST['booking_date'] : '';
            $time_slot = isset($_POST['time_slot']) ? $_POST['time_slot'] : '';

            // 参数验证
            if (!$user_id || !$coach_id || !$type || !$booking_date || !$time_slot) {
                throw new Exception('参数错误');
            }

            // 开始事务
            $conn->begin_transaction();

            try {
                // 1. 检查教练是否存在且获取价格
                $coach_sql = "SELECT price FROM coaches WHERE id = ? AND status = 1";
                $coach_stmt = $conn->prepare($coach_sql);
                if (!$coach_stmt) {
                    throw new Exception('SQL预处理失败: ' . $conn->error);
                }
                
                $coach_stmt->bind_param("i", $coach_id);
                if (!$coach_stmt->execute()) {
                    throw new Exception('教练查询失败: ' . $coach_stmt->error);
                }
                
                $coach_result = $coach_stmt->get_result();
                if ($coach_result->num_rows == 0) {
                    throw new Exception('教练不存在或已停用');
                }
                
                $coach_data = $coach_result->fetch_assoc();
                $price = $coach_data['price'];
                $coach_stmt->close();

                // 2. 检查时间段是否可用
                $schedule_sql = "SELECT id FROM coach_schedules 
                                WHERE coach_id = ? 
                                AND date = ? 
                                AND time_slot = ? 
                                AND is_available = 1 
                                AND NOT EXISTS (
                                    SELECT 1 FROM bookings 
                                    WHERE coach_id = coach_schedules.coach_id 
                                    AND booking_date = coach_schedules.date 
                                    AND time_slot = coach_schedules.time_slot 
                                    AND status < 3
                                )
                                FOR UPDATE";
                
                $schedule_stmt = $conn->prepare($schedule_sql);
                if (!$schedule_stmt) {
                    throw new Exception('SQL预处理失败: ' . $conn->error);
                }
                
                $schedule_stmt->bind_param("iss", $coach_id, $booking_date, $time_slot);
                if (!$schedule_stmt->execute()) {
                    throw new Exception('时间段查询失败: ' . $schedule_stmt->error);
                }
                
                if ($schedule_stmt->get_result()->num_rows == 0) {
                    throw new Exception('该时间段不可预约');
                }
                $schedule_stmt->close();

                // 3. 创建预约记录
                $booking_sql = "INSERT INTO bookings (user_id, coach_id, type, booking_date, 
                                           time_slot, status, price, created_at) 
                                           VALUES (?, ?, ?, ?, ?, 0, ?, NOW())";
                
                $booking_stmt = $conn->prepare($booking_sql);
                if (!$booking_stmt) {
                    throw new Exception('SQL预处理失败: ' . $conn->error);
                }
                
                $booking_stmt->bind_param("iiissd", 
                    $user_id, $coach_id, $type, $booking_date, $time_slot, $price
                );
                
                if (!$booking_stmt->execute()) {
                    throw new Exception('预约创建失败: ' . $booking_stmt->error);
                }
                $booking_id = $booking_stmt->insert_id;
                $booking_stmt->close();

                // 4. 更新教练排班状态
                $update_sql = "UPDATE coach_schedules 
                              SET is_available = 0 
                              WHERE coach_id = ? AND date = ? AND time_slot = ?";
                
                $update_stmt = $conn->prepare($update_sql);
                if (!$update_stmt) {
                    throw new Exception('SQL预处理失败: ' . $conn->error);
                }
                
                $update_stmt->bind_param("iss", $coach_id, $booking_date, $time_slot);
                if (!$update_stmt->execute()) {
                    throw new Exception('排班更新失败: ' . $update_stmt->error);
                }

                // 提交事务
                $conn->commit();
                
                echo json_encode([
                    'status' => 'success',
                    'message' => '预约成功',
                    'booking_id' => $booking_id
                ]);

            } catch (Exception $e) {
                $conn->rollback();
                throw $e;
            }
            break;

        default:
            throw new Exception('未知的操作类型');
    }

} catch (Exception $e) {
    echo json_encode([
        'status' => 'error',
        'message' => $e->getMessage()
    ]);
} finally {
    if (isset($stmt) && $stmt !== false) $stmt->close();
    if (isset($update_stmt) && $update_stmt !== false) $update_stmt->close();
    if (isset($check_stmt) && $check_stmt !== false) $check_stmt->close();
    if (isset($conn)) $conn->close();
}
?>